<template>
  <div>
    <top></top>
    <mall-header></mall-header>
    <choose-type :operation="false" :current-type-names="currentTypeNames"></choose-type>
    <div class="goods-wrapper">
      <div class="goods-left">
        <div class="image-wrapper">
          <div class="image-div">
            <pic-zoom v-if="imageList.length>0" :url="activeImageUrl" :scale="3"></pic-zoom>
          </div>
        </div>
        <div class="image-list-div">
          <div class="image-operation" @click="imageScroll('left')">
            <a-icon type="left"/>
          </div>
          <div class="image-list-wrapper">
            <div class="image-list" id="image-list">
              <div class="image" v-for="(image,index) in imageList" :key="index"
                   @click="activeImageIndex=index">
                <img :src="image" alt=""/>
              </div>
            </div>
          </div>
          <div class="image-operation right" @click="imageScroll('right')">
            <a-icon type="right"/>
          </div>
        </div>
        <supplier :data="supplierData" :active-contact-key="activeContactKey" @change="changeContact" @goShop="goShop"></supplier>
        <recommend :data="recommendList" @change="changeFocus" @detail="toDetail"></recommend>
      </div>
      <div class="goods-right">
        <div class="goods-name-wrapper">
          <div class="goods-name" :style="{color: data.isPublic ? '' : '#aaa'}">{{ data.goodsName }}</div>
          <div class="goods-type">{{ dataDictMap.DELIVERY_FORM[data.deliveryForm] }}</div>
          <a-tag color="orange" v-if="data.chargeType === 2 "> 免费 </a-tag>
          <a-tag color="orange" v-else-if="data.freeNums > 0 && data.freeDimension == 1"> 免费{{data.freeNums}}天 </a-tag>
          <a-tag color="orange" v-else-if="data.freeNums > 0 && data.freeDimension == 2"> 免费{{data.freeNums}}次 </a-tag>
          <a-tag color="blue" v-if="data.purchasePermission === 2"> 企业 </a-tag>
          <div v-if="data.authOrganFullName == '深圳数据交易所' && data.isShowFlag" class="goods-sign">
            <a-tooltip :title="'经' + data.authOrganFullName + '合规评估'">
              <img src="../../assets/z.png"/>
            </a-tooltip>
            <div class="goods-sign-text">DEXC+认证</div>
          </div>
          <!-- <div v-if="data.authOrganFullName && data.authOrganFullName != '深圳数据交易所'" style="color:#aaa;">{{data.authOrganFullName}}认证</div> -->
        </div>
        <div class="goods-desc"> {{ data.goodsDesc }} </div>
        <div class="goods-info-wrapper">
          <div class="goods-price">
            <span class="left">价格：</span>
            <template v-if="!data.activityDesc">
              {{ data.chargeType == 3 ? '面议' : ('￥' +  amount)  }}
              <span>{{ unit }}</span>
            </template>
            <template v-else>
              {{data.activityDesc}}
              <!-- <span>{{ unit }}</span> -->
              <span style="text-decoration: line-through;"> {{ (data.chargeType == 3 ? '面议' : ('￥' +  amount)) + unit }} </span>
            </template>
          </div>
          <div class="goods-id">
            商品ID：
            <span class="colorMain">{{ data.id || id }}</span>
          </div>
          <div class="goods-sales">
            累计交易：
            <span class="colorBlack">{{ data.buyTimes || 0 }}笔</span>
          </div>
          <rate-star :rate="data.goodsRate" show-bg></rate-star>
        </div>
        <div class="goods-application" v-if="data.authOrganFullName != '深圳数据交易所' && data.isShowFlag">
          <div class="goods-application-item">
            <img style="width: 14px;height:14px;margin-right: 3px;" src="../../assets/op1.png">
            互联互通：
            <span class="goods-application-item-content" :title="data.applicationIndustry">
              {{ data.authOrganFullName }}
            </span>
          </div>
        </div>
        <div class="goods-application">
          <div class="goods-application-item">
            <svg-icon icon-class="data_type" size="14" style="margin-right: 3px;"></svg-icon>
            应用行业：
            <span class="goods-application-item-content" :title="data.applicationIndustry">
              {{ data.applicationIndustry }}
            </span>
          </div>
          <div class="goods-application-item">
            <svg-icon icon-class="data_scene" size="14" style="margin-right: 3px;"></svg-icon>
            应用场景：
            <span class="goods-application-item-content" :title="data.applicationScenario">
              {{ data.applicationScenario }}
            </span>
          </div>
        </div>
        <div class="goods-spec" v-if="specList.length>0">
          <div class="goods-spec-left">规格：</div>
          <div class="goods-spec-right">
            <div class="goods-spec-item" @click="changeSpec(item,index)" v-for="(item,index) in specList" :key="index" :class="{'active':activeSpecIndex===index}">
              {{ item.showString }}
              <svg-icon v-if="activeSpecIndex===index" width="20" height="16" class="checked"
                        icon-class="checked"></svg-icon>
            </div>
          </div>
        </div>
        <div class="goods-num">
          <div class="goods-num-left">数量：</div>
          <div class="goods-num-edit">
            <a-button class="goods-num-btn-minus" icon="minus" :class="{'disabled':num<=1}" :disabled="num<=1" @click="editNum('minus')"></a-button>
            <a-input class="goods-num-input" v-model.number="num"></a-input>
            <a-button class="goods-num-btn-plus" icon="plus" @click="editNum('plus')"></a-button>
          </div>
        </div>
        <div class="goods-buy">
          <a-button type="danger" class="goods-buy-btn" @click="showConfirm">
            立即{{ data.chargeType === 3 ? '申请' : '购买' }}
          </a-button>
          <!-- <a-button v-if="data.deliveryForm==='2'" style="width: 110px;margin-left: 20px;" @click="showOnlineTest">
            接口测试
          </a-button> -->
          <div class="goods-btn-wrapper">
            <div class="goods-btn" @click="onService">
              <svg-icon size="16" icon-class="consult" style="cursor: pointer;"></svg-icon>
              <div class="goods-btn-name">联系客服</div>
            </div>
            <div class="goods-btn" @click="changeGoodFocus">
              <svg-icon size="16" :icon-class="data.focused?'focused':'focus'"></svg-icon>
              <a-icon v-show="changeFocusing" type="loading" spin/>
              <div class="goods-btn-name">
                {{ data.focused ? '取消关注' : '关注' }}
              </div>
              <div class="goods-btn-num">（{{ data.popularity || 0 }}人气）</div>
            </div>
            <div class="goods-btn">
              <svg-icon size="16" icon-class="share"></svg-icon>
              <div class="goods-btn-name">分享</div>
            </div>
          </div>
        </div>
        <div class="goods-hint" v-if="hintList.length>0">
          温馨提示：
          <div class="goods-hint-wrapper">
            <div class="goods-hint-item" v-for="(item,index) in hintList" :key="index">
              {{ item }}
            </div>
          </div>
        </div>
        <description v-if="isDecription" :isOrgan="authOrganFulIName" :active-desc-key="activeDescKey" :spec-list="specList" :api-list="data.goodsApiConfList" :id="id" :goodsEstimate="data.goodsEstimate" :goods-name="data.goodsName" :detail="data.goodsDetail" :delivery-form="data.deliveryForm" :goods-params-value-list="goodsParamsValueList" :goods-application-conf="data.goodsApplicationConf" @change="changeDesc"></description>
      </div>
    </div>
    <mall-footer></mall-footer>
    <OrderConfirm ref="orderConfirm" :show="showOrderConfirm" :data="confirmData" :loading="confirmLoading" @cancel="cancelConfirm" @ok="handleConfirm"></OrderConfirm>
    <pay-modal :visible="showPay" :receiver='receiver' :submit-loading="confirmLoading" :current-row="confirmData" @cancel="handlePayCancel" :balance="wallet?wallet.balance||0:0" @ok="handlePay"></pay-modal>
    <apply :show="showApply" :dict="dataDictLists" :user-info="userInfo" @ok="handleApply" @cancel="cancelApply"/>
    <online-test :show="showOnline" :loading="confirmLoading" :data="data" :initialApi="initialApi" :reqUrl="onlineTestUrl" :result="onlineTestResult" @cancel="cancelOnline" @ok="handleOnlineTest" @reset="resetOnline"></online-test>
  </div>
</template>

<script>
import {Modal} from 'ant-design-vue'
import Top from '@/components/base/Top'
import MallHeader from '@/components/base/MallHeader'
import Type from '@/components/Type'
import MallFooter from '@/components/base/MallFooter'
import PicZoom from 'vue-piczoom'
import Supplier from './components/Supplier'
import Recommend from './components/Recommend'
import Description from './components/Description'
import OrderConfirm from './components/OrderConfirm'
import {submitNewOrder} from '@/api/order'
import {queryGoodsInfoDetail} from '@/api/goods'
import {dictService} from '@/api/common'
import storage from '@/utils/storage'
import {queryParamByDeliveryForm} from '@/api/goods/template'
import ChooseType from '@/components/ChooseType'
import {getSupplierStore} from '@/api/review'
import { getShop } from '@/api/shop'
import {changeURLParam} from '@/utils/func'
import RateStar from '../../components/RateStar'
import {doPay} from '../../api/order'
import PayModal from './components/PayModal'
import $ from 'jquery'
import {canceledCollect, collect, collectBool} from '../../api/collect'
import Apply from './components/Apply'
import {saveGoodsNegotiate} from '../../api/negotiate'
import {listByIds} from "@/api/file";
import OnlineTest from './components/OnlineTest'
import {onlineTest} from '../../api/goods/apiConf'
import { onlineService } from '@/api/portal'
import {appConfig} from '../../config/app'
import {recommendGoodsPage} from '../../api/goods'
// import {queryPaymentWallet} from '@/api/wallet'
import walletMixin from './mixin/walletMixin'

export default {
  name: 'goodsDetail',
  mixins: [walletMixin],
  components: {
    OnlineTest,
    Apply,
    PayModal,
    RateStar,
    ChooseType,
    Top,
    MallHeader,
    Type,
    PicZoom,
    Supplier,
    Recommend,
    Description,
    OrderConfirm,
    MallFooter
  },
  data () {
    return {
      isDecription: true,
      id: '',
      authOrganFulIName: false,
      userInfo: storage.session.get('userInfo'),
      currentTypeNames: [],
      data: {
        goodsParamsValueList: [],
        goodsApiConfList: [],
        goodsApplicationConf: {}
      },
      imageList: [],
      activeImageIndex: 0,
      activeContactKey: '',
      activeDescKey: 'detail',
      recommendList: [],
      activeSpecIndex: 0,
      specList: [],
      num: 1,
      hintList: [],
      supplierData: {
        name: '',
        contactList: [],
        supplierRateList: [
          {name: '服务', rate: 0, icon: 'service'},
          {name: '质量', rate: 0, icon: 'quality'},
          {name: '价格', rate: 0, icon: 'price'},
          {name: '体验', rate: 0, icon: 'delivery'}
        ]
      },
      showOrderConfirm: false,
      confirmData: {},
      confirmLoading: false,
      dataDictMap: {
        DELIVERY_FORM: {},
        PAY_MODEL: {},
        INDUSTRY: {},
        APPLICATION_INDUSTRY: {},
        APPLICATION_SCENARIO: {},
        GOODS_CHARGE_TYPE: {}
      },
      dataDictLists: [],
      goodsParamsValueList: [],
      showPay: false,
      showApply: false,
      applyLoading: false,
      changeFocusing: false,
      recommendFocusing: false,
      showOnline: false,
      initialApi: {},
      onlineTestResult: '',
      onlineTestUrl: '',
      paymentDTO: {},
      receiver: {}
    }
  },
  computed: {
    activeImageUrl () {
      return this.imageList[this.activeImageIndex]
    },
    amount () {
      return this.specList.length > 0 ? Number(this.specList[this.activeSpecIndex].amount) : 0
    },
    unit () {
      let result = ''
      if (this.data.chargeType === 2 || this.data.chargeType === 3) {
        // 免费
        return result
      }
      const condition = this.specList.length > 0 ? this.specList[this.activeSpecIndex].condition : ''
      if (this.data.chargeDimension === 2) {
        // 按次数计费
        result = '元/' + condition + '次'
      } else {
        // 按时间计费
        if (condition) {
          result = '元/' + this.dataDictMap.GOODS_CHARGE_TYPE[condition]
        }
      }
      return result
    }
  },
  mounted () {
    this.id = this.$route.query.id
    if (this.$route.query.authorganFulIName === '深圳数据交易所') {
      this.authOrganFulIName = true
    }
    dictService(this, ['DELIVERY_FORM', 'APPLICATION_INDUSTRY', 'APPLICATION_SCENARIO', 'GOODS_CHARGE_TYPE', 'PAY_MODEL', 'INDUSTRY'])
    this.loadData()
  },
  watch: {
    num (newVal) {
      let value = newVal
      if (value) {
        value = String(value).replace(/\./g, '')
        this.num = Number(value) || ''
      }
      if (value === 0) {
        this.num = 1
      }
    },
  },
  methods: {
    async onService(){
      // let info = storage.session.get('userInfo') || {}
      // let openid = info.phone || ''

      let res = await onlineService({supplierId: this.data.supplierId, info: {type: 'goods',content: this.data.goodsName}});
      if(res.data)window.open(res.data)
    },
    goShop(){
      if (!storage.session.get('authToken') || !storage.session.get('isLogin')) return this.$message.error('请先登录')
      this.$router.push('/shop?supid=' + (this.data.supplierId || 'a0003'))
    },
    loadData () {
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      })
      queryGoodsInfoDetail({goodsInfoId: this.id, type: 1}).then(res => {
        if (res.code === 0) {
          this.data = res.data
          this.currentTypeNames = this.data.goodsTypeNameFull.split(',')
          this.currentTypeNames.splice(0, 1)
          if (this.data.goodsParamsValueList && this.data.goodsParamsValueList.length > 0) {
            this.data.applicationIndustry = this.data.goodsParamsValueList.filter(item => item.code === 'APPLICATION_INDUSTRY').map(item => item.valueName).join('')
            this.data.applicationScenario = this.data.goodsParamsValueList.filter(item => item.code === 'APPLICATION_SCENARIO').map(item => item.valueName).join('')
          }
          this.imageList = this.data.goodsImgList.filter(item => item.imgType === 1).map(item => item.imgUrl)
          this.specList = this.data.specList
          this.activeSpecIndex = 0
          this.goodsParamsValueList = this.data.goodsParamsValueList

          // if (this.data.goodsCustomParams && this.data.goodsCustomParams.length > 0) {
          //   const temp = JSON.parse(this.data.goodsCustomParams)
          //   const customParamsList = Object.keys(temp).map(item => {
          //     return {name: item, valueName: temp[item]}
          //   })
          //   this.goodsParamsValueList = this.data.goodsParamsValueList.concat(customParamsList)
          // } else {
          //   this.goodsParamsValueList = this.data.goodsParamsValueList
          // }
          // if (this.data.goodsApiConfList && this.data.goodsApiConfList.length > 0) {
          //   this.data.goodsApiConfList.forEach((item, index) => {
          //     try {
          //       const jsonObject = JSON.parse(JSON.parse(item.respondContent))
          //       this.$set(this.data.goodsApiConfList[index], 'respondContent', jsonObject)
          //     } catch (e) {
          //       console.log(e)
          //     }
          //   })
          // }

          if (storage.session.get('authToken') && storage.session.get('isLogin')) {
            this.queryIsCollect()
          }

          this.loadParamsTemplate(this.data.deliveryForm)
          this.supplierData.name = this.data.supplierName
          if (storage.session.get('authToken') && storage.session.get('isLogin')) {
            if(this.data.supplierId){
              this.getShop(this.data.supplierId)
            }
            // if (this.data.supplierName && this.data.supplierId) {
            //   this.loadSupplierData()
            // }
          }
          this.loadRecommend()
        }
      })

      // this.hintList = [
      //   '此商品为API数据接口，不支持退货',
      //   'XXXXXXXXXXXXXXXXXXXXXXXXX',
      //   'XXXXXXXXXXXXXXXXXXXXXXXXX',
      //   'XXXXXXXXXXXXXXXXXXXXXXXXX',
      //   'XXXXXXXXXXXXXXXXXXXXXXXXX',
      // ]
    },
    updatePopularity () {
      queryGoodsInfoDetail({goodsInfoId: this.id}).then(res => {
        this.changeFocusing = false
        if (res.code === 0) {
          this.$set(this.data, 'popularity', res.data.popularity)
        }
      }).catch(e => {
        console.log(e)
        this.changeFocusing = false
      })
    },
    queryIsCollect () {
      collectBool({goodsId: this.id}).then(res => {
        if (res.code === 0) {
          this.$set(this.data, 'focused', res.data !== '0')
        }
      })
    },
    loadParamsTemplate (deliveryForm) {
      if (!deliveryForm) {
        this.$message.error('商品交付形态为空')
        return
      }
      queryParamByDeliveryForm({deliveryForm: deliveryForm}).then(res => {
        if (res.code === 0) {
          const paramsTemplate = res.data
          if (this.goodsParamsValueList && this.goodsParamsValueList.length > 0) {
            this.goodsParamsValueList.forEach((item, index) => {
              if (item.code) {
                const temp = paramsTemplate.filter(param => param.code === item.code)
                const name = temp.length > 0 ? temp[0].name : ''
                if(!item.name)this.$set(this.goodsParamsValueList[index], 'name', name)
              }
            })
          }
        }
      })
    },
    async getShop(supplierId){
      let res = await getShop({supplierId})
      let { shopContact, isTrim } = res.data || {}
      shopContact = shopContact.filter(v=>v.isShow)
      this.supplierData.contactList = shopContact
      this.supplierData.isTrim = isTrim
      this.activeContactKey = shopContact.length > 0 ? shopContact[0].id : ''
    },
    loadSupplierData () {
      this.supplierData.contactList = []
      getSupplierStore({supplierId: this.data.supplierId, supplierName: this.data.supplierName}).then(res => {
        if (res.code === 0) {
          this.supplierData.contactList.push({
            ...res.data
          })
          this.supplierData.supplierRateList[0].rate = res.data.serviceScore || 0
          this.supplierData.supplierRateList[1].rate = res.data.qualityScore || 0
          this.supplierData.supplierRateList[2].rate = res.data.priceScore || 0
          this.supplierData.supplierRateList[3].rate = res.data.goodsScore || 0
          this.activeContactKey = this.supplierData.contactList.length > 0 ? this.supplierData.contactList[0].id : ''
        }
      })
    },
    loadRecommend () {
      recommendGoodsPage({page: 1, limit: 6, excludeGoodsIdList: [this.id]}).then(res => {
        if (res.code === 0) {
          this.recommendList = res.data.records
        }
      })
    },
    changeContact (e) {
      this.activeContactKey = e
    },
    changeGoodFocus () {
      if (storage.session.get('authToken') && storage.session.get('isLogin')) {
        this.changeFocusing = true
        if (this.data.focused) {
          canceledCollect({goodsId: this.id}).then(res => {
            if (res.code === 0) {
              this.$set(this.data, 'focused', !this.data.focused)
              this.updatePopularity()
            }
          }).catch(e => {
            console.log(e)
            this.changeFocusing = false
          })
        } else {
          let params = {
            goodsId: this.id
          }
          if (this.data.chargeType === 1) {
            // 收费
            params.spec = {
              amount: this.specList[this.activeSpecIndex].amount,
              condition: this.specList[this.activeSpecIndex].condition
            }
            params.specDesc = this.specList[this.activeSpecIndex].showString
          }
          collect(params).then(res => {
            if (res.code === 0) {
              this.$set(this.data, 'focused', !this.data.focused)
              this.updatePopularity()
            }
          }).catch(e => {
            console.log(e)
            this.changeFocusing = false
          })
        }
      } else {
        this.$message.error('请先登录')
      }
    },
    changeFocus (item, index) {
      if (storage.session.get('authToken') && storage.session.get('isLogin')) {
        if (this.recommendFocusing) return
        this.recommendFocusing = true
        if (item.isCollect) {
          canceledCollect({goodsId: item.goodsId}).then(res => {
            this.recommendFocusing = false
            if (res.code === 0) {
              this.$set(this.recommendList[index], 'isCollect', !item.isCollect)
            }
          }).catch(e => {
            console.log(e)
            this.recommendFocusing = false
          })
        } else {
          let params = {
            goodsId: item.goodsId
          }
          if (item.chargeType === 1) {
            // 收费
            const chargeSpecifications = JSON.parse(item.chargeSpecifications)
            params.spec = {
              amount: chargeSpecifications[0] ? chargeSpecifications[0].amount : '',
              condition: chargeSpecifications[0] ? chargeSpecifications[0].condition : ''
            }
            params.specDesc = item.specShow
          }
          collect(params).then(res => {
            this.recommendFocusing = false
            if (res.code === 0) {
              this.$set(this.recommendList[index], 'isCollect', !item.isCollect)
            }
          }).catch(e => {
            console.log(e)
            this.recommendFocusing = false
          })
        }
      } else {
        this.$message.error('请先登录')
        this.recommendFocusing = false
      }
    },
    toDetail (id) {
      this.id = id
      this.changeURLStatic('id', id)
      this.loadData()
     
    
      
      // this.showConfirm()
    },
    changeURLStatic (name, value) {
      let url = changeURLParam(location.href, name, value) // 修改 URL 参数
      history.replaceState(null, null, url) // 替换地址栏
    },
    changeSpec (item, index) {
      this.activeSpecIndex = index
    },
    async changeDesc (e) {
      console.log('e',e)
      if (e == 'third' && (!storage.session.get('authToken') || !storage.session.get('isLogin'))) return this.$message.error('请先登录');
      this.activeDescKey = e
      let { goodsEstimate } = this.data || {}
      let { estimateFileIds: fileIds } = goodsEstimate || {}
      if(!fileIds)return ;
      let res = await listByIds({fileIds})
      let { fileName, fileUrl, storageFileId, storePath } = res.data[0];
      this.data.goodsEstimate = {
        ...goodsEstimate,
        fileName, fileUrl, storageFileId, storePath
      }
    },
    editNum (type) {
      if (type === 'minus') {
        this.num = Number(this.num) - 1
      }
      if (type === 'plus') {
        this.num = Number(this.num) + 1
      }
    },
    handleApply (values) {
      this.applyLoading = true
      const params = {
        ...values,
        goodsId: this.id,
        goodsName: this.data.goodsName,
        deliveryForm: this.data.deliveryForm,
        goodsTypeId: this.data.goodsTypeId,
        supplierId: this.data.supplierId,
        supplierName: this.data.supplierName,
        supplierPhone: this.supplierData.contactList.length > 0 ? this.supplierData.contactList[0].contactPhone : '',
        supplierContactPerson: this.supplierData.contactList.length > 0 ? this.supplierData.contactList[0].contactName : ''
      }
      saveGoodsNegotiate(params).then(res => {
        this.applyLoading = false
        if (res.code === 0) {
          this.$message.success('申请成功')
          this.cancelApply()
        }
      }).catch(e => {
        console.log(e)
        this.applyLoading = false
      })
    },
    cancelApply () {
      this.applyLoading = false
      this.showApply = false
    },
    cancelOnline () {
      this.showOnline = false
      this.onlineTestResult = ''
      this.onlineTestUrl = ''
      this.initialApi = {}
    },
    resetOnline () {
      this.onlineTestResult = ''
      this.onlineTestUrl = ''
    },
    generateUrl (values) {
      let url = []
      Object.keys(values).forEach(item => {
        url.push(item + '=' + values[item])
      })
      return url.join('&')
    },
    handleOnlineTest (values) {
      const temp = JSON.parse(JSON.stringify(values))
      const tempApi = this.data.goodsApiConfList.filter(item => item.id === temp.apiInfoId)
      this.$delete(temp, 'apiInfoId')
      this.onlineTestUrl = (tempApi.length > 0 ? tempApi[0].externalUrlAddress : '') + (Object.keys(temp).length > 0 ? '?' + this.generateUrl(temp) : '')
      onlineTest(values).then(res => {
        if (res.code === 0) {
          this.onlineTestResult = res.data
        } else if (res.code === -1000) {
          this.onlineTestResult = {code: res.code, message: res.message}
        }
      }).catch(e => {
        console.log(e)
      })
    },
    showOnlineTest () {
      if (!storage.session.get('authToken') || !storage.session.get('isLogin')) {
        this.$message.error('请先登录')
        return
      }
      // const role = storage.session.get('role')
      // const roles = storage.session.get('roles')
      // if ((role && 'DATA_REQUESTER' === role) || (roles && roles.length > 0 && roles.indexOf('DATA_REQUESTER') !== -1)) {
      //   // 当前角色是需求方 或 多角色用户有需求方角色
      // } else {
      //   this.$message.error('当前登录用户没有在线测试权限')
      //   return
      // }
      this.initialApi = {
        ...this.data.goodsApiConfList[0],
        reqParamList: this.data.goodsApiConfList[0].goodsApiConfParamList.filter(item => item.type === 1)
      }
      this.showOnline = true
    },
    showConfirm () {
      // return this.queryWallet()
      if (!storage.session.get('authToken') || !storage.session.get('isLogin')) {
        return this.$message.error('请先登录')
      }
      if(!this.data.isPublic || this.data.activityDesc)return this.$info({title: '请联系商城销售',content: h => <div>服务电话：0755-88999757，<br/>邮箱：service@szdex.com，<br/>获取商品相关信息。感谢您对商城的支持！</div>})
      const role = storage.session.get('role')
      const roles = storage.session.get('roles')
      if ((role && role === 'DATA_REQUESTER') || (roles && roles.length > 0 && roles.indexOf('DATA_REQUESTER') !== -1)) {
        // 当前角色是需求方 或 多角色用户有需求方角色
      } else {
        return this.$message.error('当前登录用户没有下单权限')
      }
      if (this.data.chargeType === 3) {
        // 面议商品
        this.showApply = true
        // this.$warning({
        //   title: '提示',
        //   content: '面议数据商品需要价格与数据提供方磋商后才能交易'
        // })
        return false
      }
      if (!this.num) {
        return this.$message.error('请输入数量')
      }
      let specList = this.specList[this.activeSpecIndex] || {}
      this.confirmData = {...this.data}
      this.confirmData.spec = specList
      this.confirmData.showString = specList.showString || ''
      this.confirmData.num = this.num
      this.confirmData.amount = this.amount
      this.confirmData.total = this.num * this.amount
      this.confirmData.subAmount = this.confirmData.total
      this.confirmData.discount = 0
      const payModel = this.data.goodsParamsValueList.filter(item => item.code === 'PAY_MODEL')
      this.confirmData.payModel = payModel.length > 0 ? payModel[0].valueName : ''
      this.confirmData.payModelValue = payModel.length > 0 ? payModel[0].value : ''
      if (this.confirmData.payModelValue === '1') {
        // 预付费
        this.queryWallet()
      }else{
        this.confirmData.total = 0
        this.confirmData.subAmount = 0
        this.showOrderConfirm = true
      }
    },
    cancelConfirm () {
      this.$refs.orderConfirm && this.$refs.orderConfirm.resetData()
      this.showOrderConfirm = false
      setTimeout(() => {
        this.confirmData = {}
        this.confirmLoading = false
      }, 300)
    },
    handleConfirm (remark) {
      this.confirmLoading = true
      // 下单接口
      const params = {
        'goodsId': this.data.id,
        'num': this.num,
        'remark': remark,
        'specDesc': this.confirmData.showString,
        'spec': {
          'amount': this.confirmData.amount,
          'condition': this.confirmData.spec.condition
        }
      }
      submitNewOrder(params).then(res => {
        this.confirmLoading = false
        if (res.code === 0) {
          this.showOrderConfirm = false
          this.$message.success('提交订单成功')
          this.confirmData.orderId = res.extra.orderId
          if(this.data.chargeType === 2)return this.cancelConfirm()
          if (this.confirmData.payModelValue === '1') {
            // 预付费
            this.showPay = true
            // this.queryWallet()
          } else {
            this.cancelConfirm()
          }
        }
      }).catch(e => {
        this.confirmLoading = false
      })
    },
    async queryWallet () {
      try {
        await this.queryPaymentWallet(this.confirmData.total, this.data.supplierId)
        // let wallet = storage.session.get('wallet') || {}
        // if (!wallet.id) {
        //   Modal.info({
        //     content: '当前用户还未开通钱包',
        //     onOk(){
        //       that.cancelConfirm()
        //     }
        //   })
        //   return
        // }
        // this.showPay = true
        this.showOrderConfirm = true
      } catch (e) {
        const that = this
        Modal.error({
          content: e,
          onOk(){
            that.cancelConfirm()
          }
        })
      }
    },
    handlePay () {
      this.confirmLoading = true
      doPay({id: this.confirmData.orderId, paymentDTO: this.paymentDTO}).then(res => {
        this.confirmLoading = false
        if (res.code === 0) {
          this.$message.success('订单支付成功')
          this.getWallet()
          this.handlePayCancel()
        }
      }).catch(e => {
        console.log(e)
        this.confirmLoading = false
      })
    },
    handlePayCancel () {
      this.confirmLoading = false
      this.confirmData.orderId = undefined
      this.showPay = false
      this.cancelConfirm()
    },
    imageScroll (type) {
      if (this.imageList.length <= 4) return
      const ele = $('#image-list')
      let left = ele.css('left')
      if (left.indexOf('px') !== -1) {
        left = Number(left.split('px')[0])
      }
      const length = this.imageList.length - 4
      if (left === 0 && type === 'left') {
        return
      }
      if (type === 'right' && left <= -(length * 67)) {
        return
      }

      let offset = 67

      ele.animate({
        left: type === 'right' ? `-=${offset}px` : `+=${offset}px`
      }, 300)
    }
  }
}
</script>

<style scoped lang="scss">
$width: 1200px;
$mainColor: #0078FE;

/deep/ .ant-tag {
  background-color: #fff !important;
  padding-top: 1px;
  padding-bottom: 1px;
}


.colorMain {
  color: $mainColor;
}

.colorBlack {
  color: #323232;
}

.goods-wrapper {
  width: $width;
  margin: 20px auto;
  display: flex;
  align-items: flex-start;

  .goods-left {
    width: 300px;

    .image-wrapper {
      width: 300px;
      height: 300px;

      .image-div {
        width: 100%;
        height: 100%;
        border: 1px solid #E2E2E2;
      }
    }

    .image-list-div {
      width: 300px;
      height: 60px;
      margin-top: 10px;
      display: flex;
      align-items: center;

      .image-operation {
        width: 15px;
        height: 60px;
        border: 1px solid #efefef;
        background: #FAFAFA;
        border-radius: 4px 0 0 4px;
        color: #cbcbcb;
        display: flex;
        cursor: pointer;
        align-items: center;

        &.right {
          border-radius: 0 4px 4px 0;
        }

        &:hover {
          border-color: #ececec;
          background: #f9f9f9;
          color: #cfcfcf;
        }
      }

      .image-list-wrapper {
        flex: 1;
        width: 0;
        margin: 0 5px;
        height: 60px;
        white-space: nowrap;
        //overflow-x: auto;
        overflow: hidden;
        position: relative;

        .image-list {
          position: absolute;
          left: 0;
          display: flex;
          align-items: center;
          width: fit-content;

          .image {
            width: 60px;
            height: 60px;
            margin-right: 7px;
            cursor: pointer;
            border: 1px solid transparent;
            user-select: none;

            img {
              width: 100%;
              height: 100%;
            }

            &:last-child {
              margin-right: 0;
            }
          }
        }

        &::-webkit-scrollbar {
          display: none;
        }
      }
    }

    .goods-report {
      margin-top: 20px;
      font-size: 12px;
      font-family: PingFangSC-Regular, PingFang SC, sans-serif;
      font-weight: 400;
      color: #646464;
      line-height: 12px;

      div:first-child {
        cursor: pointer;

        &:hover {
          color: $mainColor;
        }
      }

      div:last-child {
        margin-top: 10px;
        color: #909090;
      }
    }
  }

  .goods-right {
    flex: 1;
    margin-left: 20px;

    .goods-name-wrapper {
      margin-top: 8px;
      display: flex;
      align-items: center;

      .goods-name {
        font-size: 18px;
        max-width: 76%;
        font-family: PingFangSC-Medium, PingFang SC, sans-serif;
        font-weight: 500;
        // color: #323232;
        line-height: 18px;
      }

      .goods-type {
        border-radius: 2px;
        border: 1px solid $mainColor;
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC, sans-serif;
        font-weight: 400;
        color: $mainColor;
        padding: 5px 10px;
        line-height: 12px;
        margin: 0 12px;
      }
      .goods-sign{
        display:flex;
        align-items: center;
        img{
          width: 26px;
          height:26px;
        }
        .goods-sign-text{
          color: #aaa;
          font-size: 12px;
          margin-left: 8px;
        }
      }
    }

    .goods-desc {
      font-size: 12px;
      font-family: PingFangSC-Regular, PingFang SC, sans-serif;
      font-weight: 400;
      color: #646464;
      margin-top: 12px;
      line-height: 12px;
    }

    .goods-info-wrapper {
      min-width: 880px;
      padding: 28px 20px;
      margin-top: 20px;
      background: #FFFFFF;
      box-shadow: 0 0 10px 0 rgba(0, 120, 254, 0.1);
      border-radius: 10px;
      border: 1px solid #1785FF;
      display: flex;
      align-items: center;

      .goods-price {
        display: flex;
        align-items: flex-end;
        font-size: 24px;
        font-family: PingFangSC-Medium, PingFang SC, sans-serif;
        font-weight: 500;
        color: #E03437;
        line-height: 24px;
        flex: 1;

        span {
          font-size: 12px;
          font-family: PingFangSC-Regular, PingFang SC, sans-serif;
          font-weight: 400;
          color: #646464;
          line-height: 12px;
          margin-left: 6px;
          margin-bottom: 2px;

          &.left {
            margin-left: 0;
            margin-right: 10px;
          }
        }
      }

      .goods-id {
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC, sans-serif;
        font-weight: 400;
        color: #646464;
        margin-right: 40px;
        line-height: 12px;
      }

      .goods-sales {
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC, sans-serif;
        font-weight: 400;
        color: #646464;
        line-height: 20px;
        padding-right: 20px;
        border-right: 1px dotted #e2e2e2;
        margin-right: 20px;
      }
    }

    .goods-application {
      display: flex;
      align-items: flex-start;
      margin-top: 20px;

      .goods-application-item {
        display: flex;
        align-items: flex-start;
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC, sans-serif;
        font-weight: 400;
        color: #646464;
        line-height: 14px;
        flex: 1;
        width: 0;
        overflow: hidden;
        text-overflow: ellipsis;

        //&:last-child {
        //  margin-left: 80px;
        //}

        .goods-application-item-content {
          color: #323232;
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }

    .goods-spec {
      margin-top: 10px;
      display: flex;
      align-items: flex-start;
      padding-bottom: 24px;
      border-bottom: 1px dotted #c7c7c7;

      .goods-spec-left {
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC, sans-serif;
        font-weight: 400;
        color: #646464;
        line-height: 30px;
        margin-top: 10px;
      }

      .goods-spec-right {
        flex: 1;
        display: flex;
        flex-wrap: wrap;

        .goods-spec-item {
          cursor: pointer;
          background: #FFFFFF;
          border-radius: 6px;
          border: 1px solid #E2E2E2;
          line-height: 28px;
          padding: 0 16px;
          margin-left: 10px;
          margin-top: 10px;
          position: relative;
          font-size: 12px;
          font-family: PingFangSC-Regular, PingFang SC, sans-serif;
          font-weight: 400;
          color: #323232;
          z-index: 1;

          &.active {
            border-color: #E03437;
          }

          &:hover {
            border-color: #E03437;
          }

          .checked {
            position: absolute;
            right: 0;
            bottom: 0;
            z-index: 9;
          }
        }
      }
    }

    .goods-num {
      margin-top: 20px;
      display: flex;
      align-items: center;

      .goods-num-left {
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC, sans-serif;
        font-weight: 400;
        color: #646464;
        line-height: 12px;
      }

      .goods-num-edit {
        display: flex;
        line-height: 30px;
        background: #FFFFFF;

        .goods-num-btn-minus {
          width: 32px;
          color: #646464;
          border-top-right-radius: 0;
          border-bottom-right-radius: 0;

          &.disabled {
            color: #c7c7c7;

            &:hover {
              color: #c7c7c7;
            }
          }

          &:hover {
            color: #1890ff;
          }
        }

        .goods-num-btn-plus {
          width: 32px;
          color: #646464;
          border-top-left-radius: 0;
          border-bottom-left-radius: 0;

          &:hover {
            color: #1890ff;
          }
        }

        .goods-num-input {
          width: 60px;
          border-left: none;
          text-align: center;
          border-right: none;
          border-radius: 0;
        }
      }
    }

    .goods-buy {
      margin-top: 20px;
      display: flex;
      align-items: center;

      .goods-buy-btn {
        background: #E03437;
        border-color: #E03437;
        width: 110px;
      }

      .goods-btn-wrapper {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: flex-end;

        .goods-btn {
          display: flex;
          align-items: center;
          margin-left: 30px;
          cursor: pointer;

          &:first-child {
            margin-left: 0;
          }

          &:hover {
            .goods-btn-name {
              color: $mainColor;
            }
          }

          .goods-btn-name {
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC, sans-serif;
            font-weight: 400;
            color: #323232;
            line-height: 14px;
            margin-left: 8px;
            user-select: none;

            &:hover {
              color: $mainColor;
            }
          }

          .goods-btn-num {
            font-size: 12px;
            line-height: 12px;
            font-family: PingFangSC-Regular, PingFang SC, sans-serif;
            font-weight: 400;
            color: #646464;
          }
        }
      }
    }

    .goods-hint {
      margin-top: 24px;
      line-height: 30px;
      background: #FAFAFA;
      border-radius: 4px;
      border: 1px solid #E2E2E2;
      display: flex;
      padding: 0 10px;
      font-size: 12px;
      font-family: PingFangSC-Regular, PingFang SC, sans-serif;
      font-weight: 400;
      color: #646464;

      .goods-hint-wrapper {
        flex: 1;
        width: 0;
        display: flex;
        white-space: nowrap;
        overflow-x: hidden;
        text-overflow: ellipsis;

        .goods-hint-item {
          margin-right: 60px;

          &:before {
            content: '·';
            line-height: 30px;
            font-size: 12px;
            color: #646464;
            margin-right: 4px;
          }

          &:last-child {
            margin-right: 0;
          }
        }
      }
    }
  }
}
</style>
